package com.cloud.lesson.control;

import com.cloud.lesson.enity.Payment;
import com.cloud.lesson.response.CommonResult;
import com.cloud.lesson.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: Mr.Lai
 * @createTime: 2020/12/14
 * @classNote:
 **/
@RestController
@Slf4j
@RequestMapping("/payment")
public class Controllers {
    @Autowired
    PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;


    @PostMapping(value = "/create")
    public CommonResult create(@RequestBody Payment payment){
        int i = paymentService.create(payment);
        log.info("输出下i-->:"+i);
        if(i<=0){
            return new CommonResult(false,i,"失败!serverport:"+serverPort);
        }

        return new CommonResult(true,i,"成功!serverport:"+serverPort);
    }

    @GetMapping(value = "/read/{id}")
    public CommonResult<Payment> read(@PathVariable("id") Long id){
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("***插入结果:"+paymentById+"****");
        if(paymentById == null){
            return new CommonResult(false,5050,"失败!serverport:"+serverPort);
        }

        return new CommonResult(true,10000,paymentById.toString()+"  serverport:"+serverPort);
    }

    @GetMapping(value = "/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        services.forEach(sv->{log.info("***element:{}",sv);});

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(is->{
            log.info("serviceId:{} \t Host:{} \t Port:{} \t Uri:{} \n",is.getServiceId(),is.getHost(),is.getPort(),is.getUri());
        });
        return this.discoveryClient;
    }

    @GetMapping(value = "/lb")
    public String getPaymentLb(){
        return serverPort;
    }

    @GetMapping(value = "/feign/timeout")
    public String paymentFeignTimeOut(){
        //暂停几秒钟线程
        try{
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("/zipkin")
    public String paymentZipKin(){
        return "hi , i'm a paymentzipkin server fall back, welcome to cloudlesson,O(∩_∩)O~";
    }
}
